<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 该页面已完成
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          clearable
          v-model="query.name"
          placeholder="名称"
          class="handle-input mr10"
          @keyup.native.enter="handleSearch()"
        ></el-input>

        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-if="mmtPermissions.includes('sys:mailtemplate:save')"
          >新增</el-button
        >
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="mmtPermissions.includes('sys:mailtemplate:delete')"
          >删除</el-button
        >
        <el-button
          type="primary"
          @click="handleMailConfig"
          v-if="mmtPermissions.includes('sys:mailtemplate:update')"
          >邮件配置</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="subject"
          align="center"
          label="主题"
        ></el-table-column>
        <el-table-column
          sortable
          prop="createDate"
          align="center"
          label="发送时间"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="mmtPermissions.includes('sys:mailtemplate:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="handleSendMail(scope.$index, scope.row)"
              v-if="mmtPermissions.includes('sys:mailtemplate:save')"
              >发送邮件</el-button
            >
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="mmtPermissions.includes('sys:mailtemplate:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="">
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="70px"
        :rules="rules"
      >
        <el-form-item label="名称" prop="name">
          <el-input clearable v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="主题" prop="subject">
          <el-input clearable v-model="editForm.subject"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div class="container">
            <quill-editor
              ref="myTextEditor"
              v-model="editForm.content"
              :options="addForm.editorOption"
            ></quill-editor>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="">
      <el-form ref="addForm" :model="addForm" label-width="70px" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input clearable v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="主题" prop="subject">
          <el-input clearable v-model="addForm.subject"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div class="container">
            <quill-editor
              ref="myTextEditor"
              v-model="addForm.content"
              :options="addForm.editorOption"
            ></quill-editor>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 发送邮件弹出框 -->
    <el-dialog title="发送邮件" :visible.sync="mailVisible" width="">
      <el-form
        ref="mailForm"
        :model="mailForm"
        label-width="70px"
        :rules="rules"
      >
        <el-form-item label="收件人" prop="mailTo">
          <el-input
            clearable
            v-model="mailForm.mailTo"
            placeholder="邮箱格式"
          ></el-input>
        </el-form-item>
        <el-form-item label="抄送" prop="mailCc">
          <el-input
            clearable
            v-model="mailForm.mailCc"
            placeholder="邮箱格式"
          ></el-input>
        </el-form-item>
        <el-form-item label="参数模版" prop="params">
          <el-input
            v-model="mailForm.params"
            placeholder='如: {"code": "123456"}'
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mailVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMail">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 邮件配置弹出框 -->
    <el-dialog title="邮件配置" :visible.sync="configVisible" width="50%">
      <el-form
        ref="configForm"
        :model="configForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="邮件配置" prop="smtp">
          <el-input clearable v-model="configForm.smtp"></el-input>
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input clearable v-model="configForm.port"></el-input>
        </el-form-item>
        <el-form-item label="邮箱账号" prop="username">
          <el-input clearable v-model="configForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱密码" prop="password">
          <el-input clearable v-model="configForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="configVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveConfig">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import qs from "qs";
// import { messageMailTemplateMixin } from "common/js/messageManage";
import util from "utils/util";
import { mapGetters } from "vuex";
// console.log(messageMailTemplateMixin);
export default {
  name: "messagemailtemplate",
  // mixins: [messageMailTemplateMixin],
  data() {
    var validateMail = (rule, value, callback) => {
      // console.log(value);
      if (value === "") {
        callback(new Error("必填不能为空"));
      } else {
        var pattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (!pattern.test(value)) {
          return callback(new Error("邮箱格式错误"));
        }
        callback();
      }
    };
    return {
      mmtPermissions: [],
      query: {
        order: "",
        orderField: "",
        pageIndex: 1,
        pageSize: 20,
        name: "",
      },
      tableData: [
        {
          id: "",
          name: "",
          subject: "",
          createDate: "",
        },
      ],
      multipleSelection: [],
      // ...commonVisible,
      editVisible: false,
      addVisible: false,
      mailVisible: false,
      configVisible: false,
      pageTotal: 0,
      rules: {
        name: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        subject: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        content: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        mailTo: [{ required: true, validator: validateMail, trigger: "blur" }],
        smtp: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        port: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        username: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
      },
      // 邮件配置
      configForm: {
        smtp: "",
        port: "",
        username: "",
        password: "",
      },
      // 发送邮件
      mailForm: {
        id: "",
        mailTo: "",
        mailCc: "",
        params: "",
      },
      editForm: {
        id: "",
        name: "",
        subject: "",
        content: "",
        editorOption: {
          placeholder: "Hello World",
        },
      },
      addForm: {
        id: "",
        name: "",
        subject: "",
        content: "",
        editorOption: {
          placeholder: "Hello World",
        },
      },
      idx: -1,
      ids: [],
    };
  },
  methods: {
    // 获取数据
    getMesMailTempData({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      name = this.query.name,
      _t = Date.now(),
    }) {
      this.$axios
        .get("/sys/mailtemplate/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            name,
            _t,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          // console.log(res);
          this.tableData = res.data.list;
          this.pageTotal = res.data.total || 0;
        })
        .catch(() => {});
    },

    // 表头排序
    sortChange({ column, prop, order }) {
      // console.log(column, prop, order);
      prop = prop === "createDate" ? "create_date" : prop;
      this.$set(this.query, "orderField", prop);
      if (order === "ascending") {
        this.$set(this.query, "order", order.substr(0, 3));
        this.getMesMailTempData({});
      } else if (order === "descending") {
        this.$set(this.query, "order", order.substr(0, 4));
        this.getMesMailTempData({});
      }
    },
    // 邮件配置
    handleMailConfig() {
      this.configVisible = true;
      this.$axios
        .get("/sys/mailtemplate/config", {
          params: {
            _t: Date.now(),
          },
        })
        .then(({ data: res }) => {
          // console.log(res);
          if (res.code !== 0) {
            return;
          }
          this.configForm = res.data;
        })
        .catch(() => {});
    },
    // 邮件配置
    saveConfig() {
      this.$axios
        .post("/sys/mailtemplate/saveConfig", {
          smtp: this.configForm.smtp,
          port: this.configForm.port,
          username: this.configForm.username,
          password: this.configForm.password,
        })
        .then(({ data: res }) => {
          // console.log(res);
          if (res.code !== 0) {
            return;
          }
          this.configVisible = false;
          this.$message.success("操作成功");
          this.getMesMailTempData({});
        })
        .catch(() => {});
    },
    // 发送邮件
    handleSendMail(index, row) {
      // console.log(index, row);

      this.mailVisible = true;
      this.mailForm.id = row.id;
    },
    saveMail() {
      this.$axios
        .post(
          "/sys/mailtemplate/send",
          qs.stringify({
            id: this.mailForm.id,
            mailTo: this.mailForm.mailTo,
            mailCc: this.mailForm.mailCc,
            params: JSON.stringify({ code: this.mailForm.params }),
          }),
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          }
        )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }

          this.$message.success("发送成功"); // params参数格式不确定
          this.mailVisible = false;
          this.getMesMailTempData({});
        })
        .catch(() => {});
    },
    // 编辑操作
    handleEdit(index, row) {
      // console.log(index, row);
      this.idx = index;
      // this.editForm = row;   // 由后台返回数据填充,
      this.editVisible = true;
      this.$axios
        .get("/sys/mailtemplate/" + row.id, {
          _t: Date.now(),
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.editForm = res.data;
        })
        .catch(() => {});
    },
    // 保存编辑
    saveEdit() {
      this.editVisible = false;
      // 得到成功提示
      this.$axios
        .put(
          "/sys/mailtemplate",
          qs.stringify({
            id: this.editForm.id,
            name: this.editForm.name,
            subject: this.editForm.subject,
            content: this.editForm.content,
            createDate: "",
          })
        )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getMesMailTempData({});
        })
        .catch(() => {});
    },
    // 富文本
    onEditorChange({ editor, html, text }) {
      this.addForm.content = html;
    },

    // 新增弹出框
    saveAdd() {
      this.addVisible = false;
      // 得到成功提示
      this.$axios
        .post(
          "/sys/mailtemplate",
          qs.stringify({
            name: this.addForm.name,
            subject: this.addForm.subject,
            content: `${this.addForm.content},`,
            createDate: "",
          }),
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          }
        )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");
          this.getMesMailTempData({});
        })
        .catch(() => {});
    },
    // 新增
    handleAdd() {
      this.addVisible = true;
    },

    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.$set(this.query, "pageIndex", 1);
      var params = {
        order: this.query.order,
        orderField: this.query.orderField,
        page: this.query.pageIndex,
        limit: this.query.pageSize,
        name: this.query.name,
        _t: Date.now(),
      };
      this.tableData = [];
      this.getMesMailTempData(params);
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(
        this,
        "/sys/mailtemplate",
        index,
        this.ids,
        this.getMesMailTempData
      );
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      util.delete.call(
        this,
        "/sys/mailtemplate",
        "",
        ids,
        this.getMesMailTempData
      );
    },

    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getMesMailTempData({});
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getMesMailTempData({});
    },
  },

  created() {
    this.getMesMailTempData({});
    this.mmtPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/message-mail-template") {
        this.mmtPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.mmtPermissions = newVal;
    },
  },
  components: { quillEditor },
  // methods: {
  // }
};
</script>

<style scoped>
@import url("../../common/css/index.css");
</style>
